package cn.itcast.user.controller;

import cn.itcast.user.vo.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @program: springcloud-demo2
 * @description:
 * @author: sch
 * @create: 2023-04-02 12:16
 **/
@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    private String url = "http://localhost:8083/order/";
    private String url2 = "http://itcast-order-nacos/order/";

    @RequestMapping("hello")
    public String hello() {
        String msg = restTemplate.getForObject(url + "hello", String.class);
        return "hello user <===>" + msg;
    }

    @RequestMapping("hello2")
    public String hello2() {
        String msg = restTemplate.getForObject(url2 + "hello", String.class);
        return "hello user <===>" + msg;
    }

    @RequestMapping("list")
    public String list() {
        System.out.println("user===>list...");
        String str = restTemplate.getForObject(url + "orderList", String.class);
        System.out.println(str);
        return "user===>list--->" + str;
    }

    @RequestMapping("list2")
    public String list2() {
        System.out.println("user===>list2...");
        String str = restTemplate.getForObject(url2 + "/orderList", String.class);
        return "user===>list2--->" + str;
    }

    @RequestMapping("findOrderByUserId")
    public List findOrderByUserId(Long userId) {
        List resp = restTemplate.getForObject(url + "findOrderByUserId?userId=" + userId, List.class);

        System.out.println("order.findOrderByUserId查询成功" + resp);
        return resp;
    }

    /**
     * 表单提交
     *
     * @return
     */
    @RequestMapping("addOrder")
    public String addOrder() {
        System.out.println("user===>addOrder...");
        //对于表单参数，使用LinkedMultiValueMap来进行封装
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("orderNo", 341222205L);
        map.add("orderSource", "itcast2");
        map.add("createrUser", "ruhua2");
        map.add("userId", 2L);

        ResponseEntity<String> response = restTemplate.postForEntity(url + "addOrder", map, String.class);
        return "add--->" + response.getBody();
    }

    @RequestMapping("addOrder2")
    public String addOrder2() {
        System.out.println("user===>addOrder2...");
        //发送POST，而且是JSON参数,在web里面默认会使用jackson，会将对象转为字符串
        OrderInfoVo orderInfoVo = new OrderInfoVo(341222204L, "itcast", "xiaoqiang04", 2L);
        ResponseEntity<String> response = restTemplate.postForEntity(url + "addOrder2", orderInfoVo, String.class);
        return "add2--->" + response.getBody();
    }

}
